package com.shfl.servermanage.logic.api.bt;

import cn.hutool.json.JSONUtil;
import com.shfl.servermanage.bt.BtComponent;
import com.shfl.servermanage.bt.BtConstants;
import com.shfl.servermanage.common.ApiResultHelper;
import com.shfl.servermanage.common.SystemConstant;
import com.shfl.servermanage.logic.model.bt.info.AddRemoteSiteResultInfo;
import com.shfl.servermanage.logic.model.info.BtUserInfo;
import com.shfl.servermanage.logic.model.request.AddSiteRequest;
import com.shfl.servermanage.logic.service.SysServerBtService;
import com.shfl.servermanage.logic.service.SysServerSiteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
//@PreAuthorize("isAuthenticated()")
@RequestMapping("/api/bt/site")
@Api("宝塔站点")
public class BtSiteController {
    @Autowired
    private BtComponent btComponent;

    @Autowired
    private SysServerBtService sysServerBtService;

    @Autowired
    private SysServerSiteService sysServerSiteService;


    @PostMapping(value = "/add")
    @ApiOperation(value = "新增站点", notes = "新增站点")
    public ApiResultHelper addSite(
            @RequestBody AddSiteRequest addSiteRequest
    ) throws Exception {
        BtUserInfo info = sysServerBtService.findBtUserInfo(addSiteRequest.getServiceId());
        info.setApiUrl(BtConstants.ADD_SITE);

        String path = info.getRootDirectory().concat("/" + addSiteRequest.getSiteDomain());
        Map<String, Object> map = new HashMap<>();
        map.put("webname", "{\"domain\":\"" + addSiteRequest.getSiteDomain() + "\",\"domainlist\":[],\"count\":0}");
        map.put("type", "PHP");
        map.put("port", addSiteRequest.getSitePort());
        map.put("ps", addSiteRequest.getSiteDomain());
        map.put("path", path);
        map.put("type_id", 0);
        map.put("version", addSiteRequest.getPhpVersion());
        map.put("ftp", false);
        map.put("sql", false);
        map.put("codeing", "utf8");
        String resultString = btComponent.send(info, map);
        AddRemoteSiteResultInfo resultData = JSONUtil.parse(resultString).getByPath("", AddRemoteSiteResultInfo.class);
        addSiteRequest.setRemoteSiteId(resultData.getSiteId());
        addSiteRequest.setSiteDirectory(path);
        sysServerSiteService.add(addSiteRequest);
        return new ApiResultHelper(SystemConstant.RE_SUCCESS_CODE);
    }


}
